<template>
  <div class="edit">
    <van-nav-bar title="编辑资料" left-arrow @click-left="$router.back()" />
    <div class="avatar">
      <van-image round fit="cover" :src="userInfo.photo" />
      <!-- 图片预览 -->
      <van-uploader :after-read="afterRead" />
    </div>
    <van-cell
      @click="showNameDialog"
      title="名称"
      :value="userInfo.name"
      is-link
    />
    <van-cell
      @click="popShow = true"
      title="性别"
      :value="userInfo.gender ? '男' : '女'"
      is-link
    />
    <van-cell
      @click="showBrith"
      title="生日"
      :value="userInfo.birthday"
      is-link
    />

    <van-dialog
      class="dialog-name"
      v-model="dialogShow"
      title="修改名称"
      @confirm="changeName"
      show-cancel-button
    >
      <van-field ref="nameInp" v-model="editName" />
    </van-dialog>

    <!-- 修改性别 -->
    <van-popup v-model="popShow" position="bottom" :style="{ height: '18%' }">
      <van-nav-bar
        title="修改性别"
        left-text="取消"
        @click-left="popShow = false"
      />
      <van-cell-group>
        <van-cell title="男" @click="changsex(1)" is-link />
        <van-cell title="女" @click="changsex(0)" is-link />
      </van-cell-group>
    </van-popup>

    <!-- 修改生日时间 -->
    <van-popup v-model="birthShow" position="bottom" :style="{ height: '30%' }">
      <van-datetime-picker
        @confirm="changeBirthday"
        v-model="currentDate"
        type="date"
        title="选择年月日"
        :min-date="minDate"
        :max-date="maxDate"
      />
    </van-popup>
    <div class="crop-wrap" v-show="cropShow">
      <vueCropper
        ref="cropper"
        :img="cropImg"
        autoCrop
        autoCropWidth="150"
        autoCropHeight="150"
      ></vueCropper
      >\
      <van-button @click="doCrop" type="primary">裁剪</van-button>
      <van-button @click="cropShow = false" type="primary">取消</van-button>
    </div>
  </div>
</template>

<script>
import moment from "moment";
import { VueCropper } from "vue-cropper";
import { editProfileAPI, editAvatarAPI } from "@/api";
export default {
  async created() {
    // console.log(111);
    // let res = await userInfoAPI();
    // // console.log(res);
    // this.info = res.data.data;
    // this.$store.commit("setUserInfo", res.data.data);
    this.$store.dispatch("reqUserInfo");
  },
  computed: {
    userInfo() {
      return this.$store.state.userInfo;
    },
  },
  components: {
    VueCropper,
  },
  data() {
    return {
      dialogShow: false,
      editName: "",
      popShow: false,
      birthShow: false,
      currentDate: new Date(),
      minDate: new Date("1990-01-01"),
      maxDate: new Date(),
      cropShow: false,
      cropImg: "",
    };
  },
  methods: {
    showNameDialog() {
      this.dialogShow = true;

      this.editName = this.userInfo.name;
      this.$nextTick(() => {
        // 等下一次dom渲染完毕，再去找到input，再让它获得焦点
        this.$refs.nameInp.focus();
      });
    },
    // 修改昵称
    async changeName() {
      await editProfileAPI({
        name: this.editName,
      });
      this.$store.commit("setUserInfo", {
        ...this.$store.state.userInfo,
        name: this.editName,
      });
    },
    // 修改性别
    async changsex(gender) {
      if (gender === this.userInfo.gender) return (this.popShow = false);
      await editProfileAPI({
        gender,
      });
      this.$store.commit("setUserInfo", {
        ...this.$store.state.userInfo,
        gender,
      });
      this.popShow = false;
    },
    // 生日cell点击事件-显示生日选择器
    showBrith() {
      this.currentDate = new Date(this.userInfo.birthday);
      this.birthShow = true;
    },
    // 修改年龄
    async changeBirthday(value) {
      const birthday = moment(value).format("YYYY-MM-DD");
      await editProfileAPI({
        birthday,
      });
      this.$store.commit("setUserInfo", {
        ...this.$store.state.userInfo,
        birthday,
      });
      this.birthShow = false;
    },
    // 图片预览
    afterRead(file) {
      console.log(file);
      // file里包含了当前选择的文件信息
      // content属性有选择的图片对应的base64编码
      // 此时可以自行将文件上传至服务器
      console.log("选择完文件了", file.content);
      // file属性就有这张文件对象
      console.log("选择完文件了", file.file);
      this.cropShow = true;
      this.cropImg = file.content;
    },
    doCrop() {
      // 要不要拿到框选后裁剪的结果
      this.$refs.cropper.getCropBlob(async (data) => {
        // do something
        // console.log(data);
        // 而ajax要传文件，必须要依赖 FormData 对象
        let fm = new FormData(); // 空的
        // 添加内容,参数1：key 参数2：值
        fm.append("photo", data);

        let res = await editAvatarAPI(fm);
        // 隐藏裁剪框
        this.cropShow = false;
        // 把上传后的图片最新地址传递到vuex
        this.$store.commit("setUserInfo", {
          ...this.$store.state.userInfo,
          photo: res.data.data.photo,
        });
        this.$toast.success("修改成功！");
      });
    },
  },
};
</script>

<style lang="less">
.edit {
  .avatar {
    height: 140px;
    display: flex;
    justify-content: center;
    align-items: center;
    position: relative;
    .van-image {
      width: 120px;
      height: 120px;
    }
    .van-uploader {
      width: 100%;
      height: 100%;
      position: absolute;
      opacity: 0;

      .van-uploader__wrapper {
        width: 100%;
        height: 100%;

        .van-uploader__upload {
          width: 100%;
          height: 100%;
        }
      }
    }
  }
  .dialog-name {
    .van-field {
      border: 1px solid #ddd;
    }
  }
  .crop-wrap {
    // 铺满整个屏幕
    // vw: viewport width 视口宽度
    // vh：viewport height 视口高度
    // 把视口宽度和高度各自分成100份，写100代表铺满
    width: 100vw;
    height: 100vh;
    position: fixed;
    left: 0;
    top: 0;
    background-color: #f00;
    .van-button {
      position: fixed;
      bottom: 0;
      left: 0;

      &:nth-of-type(2) {
        // 要把left给恢复成默认值
        left: auto;
        right: 0;
      }
    }
  }
}
</style>